package org.example.kidscode.controller;

import org.example.kidscode.entity.Course;
import org.example.kidscode.service.CourseService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@CrossOrigin
@RestController
@RequestMapping("/api/courses")
public class CourseController {

    private final CourseService courseService;

    public CourseController(CourseService courseService) {
        this.courseService = courseService;
    }

    @GetMapping
    public List<Course> getAllCourses() {
        return courseService.findAll();
    }

    @GetMapping("/{id}")
    public Optional<Course> getCourse(@PathVariable String id) {
        return courseService.findById(id);
    }

    @PostMapping
    public Course createCourse(@RequestBody Course course) {
        return courseService.save(course);
    }

    @DeleteMapping("/{id}")
    public void deleteCourse(@PathVariable String id) {
        courseService.deleteById(id);
    }

    @GetMapping("/teacher/{teacherId}")
    public List<Course> getByTeacher(@PathVariable String teacherId) {
        return courseService.findByTeacher(teacherId);
    }

    @GetMapping("/type/{courseType}")
    public List<Course> getByType(@PathVariable String courseType) {
        return courseService.findByType(courseType);
    }

    @PutMapping("/{id}")
    public Course updateCourse(@PathVariable String id, @RequestBody Course course) {
        // 确保 courseId 一致
        course.setCourseId(id);
        return courseService.save(course);
    }
}
